package com.ujs.eduservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ujs.commonutils.constant.R;
import com.ujs.commonutils.utils.JwtUtils;
import com.ujs.eduservice.entity.EduComment;
import com.ujs.eduservice.entity.EduTeacher;
import com.ujs.eduservice.entity.vo.frontVo.CommentVo;
import com.ujs.eduservice.entity.vo.frontVo.Member;
import com.ujs.eduservice.feign.UcenterFeignService;
import com.ujs.eduservice.mapper.EduCommentMapper;
import com.ujs.eduservice.service.EduCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ujs.servicebase.entity.MemberVoOrder;
import com.ujs.servicebase.exception.GuliException;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static com.ujs.commonutils.utils.PackageListPage.packageListPage;

/**
 * <p>
 * 评论 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2023-09-03
 */
@Service
public class EduCommentServiceImpl extends ServiceImpl<EduCommentMapper, EduComment> implements EduCommentService {
    @Autowired
    private UcenterFeignService ucenterFeignService;

    @Override
    public Map<String, Object> getCommentList(String courseId, Long page, Long limit) {
        Page<EduComment> commentPage = new Page<>(page, limit);
        QueryWrapper<EduComment> queryWrapper = new QueryWrapper<EduComment>().eq("course_id", courseId).orderByDesc("gmt_create");
        baseMapper.selectPage(commentPage, queryWrapper);
        return packageListPage(commentPage, queryWrapper);
    }

    @Override
    public void addComment(CommentVo commentVo, HttpServletRequest request) {
        // 设置评论属性
        EduComment eduComment = new EduComment();
        BeanUtils.copyProperties(commentVo, eduComment);
        // 设置用户内容
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)) {
            throw new GuliException(20001, "请先登录");
        }
        MemberVoOrder memberInfoById = ucenterFeignService.getMemberInfoById(memberId);
        if (memberInfoById != null) {
            eduComment.setMemberId(memberId);
            eduComment.setNickname(memberInfoById.getNickname());
            eduComment.setAvatar(memberInfoById.getAvatar());
            int insert = baseMapper.insert(eduComment);
            if (insert == 0) {
                throw new GuliException(20001, "添加数据库失败");
            }
        }
    }
}
